<?php
class Room_Controller extends AdminController {

    public $DISPLAY_LOCALIZED_VALUE_LIST_UUID = 'admin/room/display/localizedValueList';

    public function __construct() {
        parent::__construct('room');
        $this->setDefaultListOrder('code');
    }

    function all() {
        $this->initPagination('room');

        $this->viewData['roomList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT room.*, l10n.* ' .
                'FROM room ' .
                'LEFT OUTER JOIN room_l10n l10n ON room.code = l10n.room_code AND l10n.language_code = :language_code'),
                array('language_code' => $this->getLocalLanguageCode()));
        $this->renderSubview('admin/room/roomList');
    }

    function display() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $room = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
        if (! $room) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['room'] = $room;

        $this->viewData['roomL10nList'] = $this->dao->queryAll(sql::orderBy($this->DISPLAY_LOCALIZED_VALUE_LIST_UUID,
                'SELECT l10n.*, l.name as language_name FROM room_l10n l10n ' .
                'LEFT OUTER JOIN language l ON l.code = l10n.language_code ' .
                'WHERE l10n.room_code = :code', 'room_code'),
                array('code' => $code));
        
        $this->loadFormData();

        $this->renderSubview('admin/room/roomDisplay');
    }

    function edit() {
        $code = $this->input->get('code');

        if ($code) {
            if (! valid::isCode($code)) {
                $this->redirectToList('error.invalidId');
            }

            $room = $this->dao->getByCode('room', $code);
            if (! $room) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // default values for a new record
            $room = array(
                'language_code' => $this->getLocalLanguageCode()
            );
        }
        
        $this->loadFormData();

        $this->viewData['room'] = $room;
        $this->renderSubview('admin/room/roomEdit');
    }

    protected function loadFormData() {
        $this->viewData['languageOptions'] = $this->dao->queryOptions(
                'SELECT l.code, l.name ' .
                'FROM language l ' .
                'ORDER BY l.name');
        $this->viewData['genderOptions'] = array(
            'M' => text::get('room-gender-M'),
            'F' => text::get('room-gender-F')
        );
        $this->viewData['accomodationTypeOptions'] = $this->dao->queryOptions(
                'SELECT accomodation_type_code, name FROM accomodation_type_l10n ' .
                'WHERE language_code = :language_code ORDER BY name',
                array('language_code' => $this->getLocalLanguageCode()));
        $this->viewData['buildingOptions'] = $this->dao->queryOptions(
                'SELECT building_code, name FROM building_l10n ' .
                'WHERE language_code = :language_code ORDER BY name',
                array('language_code' => $this->getLocalLanguageCode()));
    }

    public function save() {
        $formData = $this->postToDbValues();
        $code = $formData['code'];
        $this->viewData['room'] = $formData;

        // Basic validation
        $validator = new EntityValidator($formData, 'room', $this->msg);
        $validator->code('code');
        $validator->code('building_code');
        if (! sql::isPersistent($formData)) {
            $validator->code('language_code');
            $validator->required('name');
            $validator->required('description');
        }
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/room/roomEdit');
            return;
        }

        if (! sql::isPersistent($formData)) {
            // Database validation - unique name
        	$existingEntity = $this->dao->getByCode('room', $code);
        	if ($existingEntity) {
        		$this->msg->error('room.error-alreadyExists-code', $code);
        	}
            if ($this->dao->alreadyExists('room_l10n', array('name', 'language_code'), array_merge(array('room_code' => $code), $formData), 'room_code')) {
                $this->msg->error('room.error-alreadyExists-name', $formData['name']);
            }
        }
        else {
            $existingRoom = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
            if (! $existingRoom) {
                $this->msg->error('error.recordNotFound');
            }
        }
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/room/roomEdit');
            return;
        }

        // Insert or update
        $roomEntity = new RoomEntity($formData);
        if ($roomEntity->isPersistent()) {
            $this->dao->updateEntity($roomEntity);
            $this->msg->info('room.editSuccess', $existingRoom['name']);
        }
        else {
            $this->dao->insertEntity($roomEntity);
            
            // Insert localized values
            $roomL10nEntity = new RoomL10nEntity($formData);
            $this->dao->insertEntity($roomL10nEntity);
            $this->msg->info('room.createSuccess', $roomL10nEntity->get('name'));
        }
        
        $this->ajaxSuccessOrRedirect('/admin/room/display?code=' . $code, $formData);
    }

    function delete() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        // Basic validation
        $room = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
        if (! $room) {
            $this->redirectToList('error.recordNotFound');
        }

        // Delete the record, localization values are deleted by cascading.
        $this->dao->deleteByCode('room', $code);

        $this->msg->info('room.deleteSuccess', $room['name']);
        $this->redirectToList();
    }

    function editLocalizedValues() {
        $code = $this->input->get('room_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $room = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
        if (! $room) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['room'] = $room;

        if (valid::isCode($languageCode)) {
            $formData = $this->dao->getUnique('room_l10n',
                    array(
                        'room_code' => $code,
                        'language_code' => $languageCode
                    ));
            if (! $formData) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // Default values
            $formData = array('room_code' => $code);
        }
        $this->viewData['formData'] = $formData;

        $this->localizedValuesData($code, $languageCode);
        $this->renderMySubview('roomL10nEdit');
    }

    function localizedValuesData($roomCode, $languageCode) {
        $params = array('code' => $roomCode);
        $query = 'SELECT l.code, l.name ' .
                    'FROM language l ' .
                    'WHERE l.code NOT IN (SELECT l10n.language_code FROM room_l10n l10n WHERE l10n.room_code = :code) ';
        if ($languageCode) {
            $query .= 'OR l.code = :language_code ';
            $params['language_code'] = $languageCode;
        }
        $query .= 'ORDER BY l.name';
        $this->viewData['languageOptions'] = $this->dao->queryOptions($query, $params);
    }

    function saveLocalizedValues() {
        $formData = $this->postToDbValues();
        $code = $formData['room_code'];
        $this->viewData['formData'] = $formData;
        $languageCode = $formData['language_code'];
        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $room = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
        if (! $room) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['room'] = $room;

        // Basic validation
        $validator = new EntityValidator($formData, 'room', $this->msg);
        $validator->code('language_code');
        $validator->required('name');
        $validator->required('description');
        if ($this->msg->hasErrors()) {
            $this->localizedValuesData($code, $languageCode);
            $this->publishErrors('admin/room/roomL10nEdit');
            return;
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $roomL10nEntity = new RoomL10nEntity($formData);
        
        if (! $roomL10nEntity->isPersistent()) {
            // Check if we don't have already this language
            $existingL10n = $this->dao->getByPrimaryKey($roomL10nEntity);
            if ($existingL10n) {
                $this->msg->error('errors.translationAlreadyExists', $language['name']);
                $this->localizedValuesData($code, $languageCode);
                $this->publishErrors('admin/room/roomL10nEdit');
            }

            $this->dao->insertEntity($roomL10nEntity);
            $this->msg->info('room.createL10nSuccess', $roomL10nEntity->get('name'), $language['name']);
        }
        else {
            $this->dao->updateEntity($roomL10nEntity);
            $this->msg->info('room.editL10nSuccess', $roomL10nEntity->get('name'), $language['name']);
        }

        $this->redirect('/admin/room/display?code=' . $code);
    }

    function deleteLocalizedValues() {
        $code = $this->input->get('room_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code) || ! valid::isCode($languageCode)) {
            $this->redirectToList('error.invalidId');
        }

        $room = $this->dao->getLocalizedEntityByCode('room', $code, $this->getLocalLanguageCode());
        if (! $room) {
            $this->redirectToList('error.recordNotFound');
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $roomL10nEntity = new RoomL10nEntity($_GET);

        $existingRecord = $this->dao->getByPrimaryKey($roomL10nEntity);
        if (! $existingRecord) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->dao->deleteEntity($roomL10nEntity);

        $this->msg->info('room.deleteL10nSuccess', $room['name'], $language['name']);
        $this->redirect('/admin/room/display?code=' . $code);
    }
    
    function orderForm() {
        $this->viewData['roomList'] = $this->dao->queryAll(
                'SELECT room.*, l10n.* ' .
                'FROM room ' .
                'LEFT OUTER JOIN room_l10n l10n ON room.code = l10n.room_code AND l10n.language_code = :language_code ' .
                'ORDER BY room.order_number', 
                array('language_code' => $this->getLocalLanguageCode()));
        $this->renderSubview('admin/room/roomOrder');
    }
    
    function orderSave() {
        $itemOrder = $this->input->post('itemOrder');
        $index = 1;
        foreach ($itemOrder as $code) {
            $room = $this->dao->getByCode('room', $code);
            $room['order_number'] = $index;
            $this->dao->update('room', $room, 'code');
            $index++;
        }
        $this->msg->info('application.orderSave-success');
        $this->redirect('/admin/room/all');
    }
}
